import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

from core.config import settings
from core.exception import ApiException, api_exception_handler
import logging


from routers import chat,doc,pan,small_chat,knowledge_router, maxkb_router

# from routers import chat
app = FastAPI(
    title=settings.APP_NAME,
    description="AI智能体中心API服务",
    version="1.0.0"
)
app.include_router(chat.router)
app.include_router(doc.router)
app.include_router(pan.router)
app.include_router(small_chat.router)
app.include_router(knowledge_router.router)
app.include_router(maxkb_router.router)

# 允许所有域名跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有 HTTP 方法
    allow_headers=["*"],  # 允许所有请求头
)


# 注册异常处理器
app.add_exception_handler(ApiException, api_exception_handler)

logging.basicConfig(
    filename="app.log",
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S"
)

logging.info("AI智能体启动成功")


# 测试Redis聊天记录功能的临时端点
@app.get("/test_redis_chat")
async def test_redis_chat():
    from services.chat_service import ChatService
    import logging
    logger = logging.getLogger(__name__)
    
    try:
        chat_service = ChatService()
        test_account_no = "test_user_123"
        
        # 测试添加用户消息
        logger.debug("开始测试添加用户消息")
        user_add_result = await chat_service.add_message(test_account_no, "你好，这是测试消息", "user")
        logger.debug(f"用户消息添加结果: {user_add_result}")
        
        # 测试添加助手消息
        logger.debug("开始测试添加助手消息")
        assistant_add_result = await chat_service.add_message(test_account_no, "您好！我是AI助手", "assistant")
        logger.debug(f"助手消息添加结果: {assistant_add_result}")
        
        # 测试获取聊天历史
        logger.debug("开始测试获取聊天历史")
        history = await chat_service.get_chat_history(test_account_no)
        logger.debug(f"获取到的聊天历史数量: {len(history)}")
        
        # 测试批量保存
        logger.debug("开始测试批量保存")
        batch_result = await chat_service.save_chat_message(
            test_account_no, 
            "这是测试批量保存的用户消息", 
            "这是测试批量保存的助手消息"
        )
        logger.debug(f"批量保存结果: {batch_result}")
        
        # 再次获取聊天历史验证
        final_history = await chat_service.get_chat_history(test_account_no)
        logger.debug(f"批量保存后聊天历史数量: {len(final_history)}")
        
        return {
            "status": "success",
            "user_add_result": user_add_result,
            "assistant_add_result": assistant_add_result,
            "history_count": len(history),
            "batch_result": batch_result,
            "final_history_count": len(final_history),
            "final_history": final_history
        }
    except Exception as e:
        logger.error(f"测试Redis聊天功能失败: {str(e)}", exc_info=True)
        return {
            "status": "error",
            "message": str(e)
        }

@app.get("/")
async def root():
    return {
        "message": "欢迎使用AI智能体中心API",
        "version": "1.0.0",
        "available_agents": ["chat", "doc", "pan", "small_chat", "knowledge", "maxkb"] # 列出可用的智能体
    }




if __name__ == '__main__':
    uvicorn.run(app, port=10031, host="0.0.0.0")